<template>
  <view class="relative min-100vh flex flex-column justify-between test">
    <view>
      <u-navbar title="巡检项详情" :background="{ backgroundColor:'#9CE0FF'}" :border-bottom="false" title-color="#000" title-size="37" />
      <sub-title class="mt-20" title="异常信息"></sub-title>
      <view class="p-lr-40 mb-20">
        <view class="fz-30 lh-42 color-888888 mt-20 flex w-full">
          <text class="w-150 block">异常工单</text>
          <view class="flex1 text-right color-2D8CF0 break-all">
            <text @tap="toAssignmentDetail">{{abnormalInfo.workOrderName ? `${abnormalInfo.workOrderName}>` : '-'}}
            </text>
          </view>
        </view>
        <view class="fz-30 lh-42 color-888888 mt-10 flex">
          <text class="w-150">异常位置</text>
          <view class="flex1 text-right">
            <text>{{ abnormalInfo.roomName || '-'}}</text>
          </view>
        </view>
        <view class="fz-30 lh-42 color-888888 mt-10 flex">
          <text class="w-150">异常设备</text>
          <view class="flex1 text-right">
            <text>{{ abnormalInfo.deviceName || '-'}}</text>
          </view>
        </view>
        <view class="fz-30 lh-42 color-888888 mt-10 flex">
          <text class="w-150">上报时间</text>
          <view class="flex1 text-right">
            <text>{{ abnormalInfo.createTime || '-'}}</text>
          </view>
        </view>
        <view class="fz-30 lh-42 color-888888 mt-10 flex">
          <text class="w-150">上报人员</text>
          <view class="flex1 text-right">
            <text>{{ abnormalInfo.staffName || '-'}}</text>
          </view>
        </view>
        <view class="fz-30 lh-42 color-888888 mt-10">
          <text>异常状态</text>
          <text class="f-r" :class="[(isFixed || abnormalInfo.status == 1) ?'color-19BE6B':'color-FF6262']">{{ (isFixed || abnormalInfo.status == 1) ? '已解决' : '待解决' }}</text>
        </view>
      </view>

      <sub-title title="异常详情"></sub-title>
      <view class="p-tb-20 p-lr-40 fz-32 lh-45 w-full wrap">
        <text>{{ abnormalInfo.detail || '-'}}</text>
      </view>

      <sub-title title="现场图片"></sub-title>
      <view class="p-lr-40 pt-20 pb-10">
        <view class="flex flex-wrap" v-if="errphotoFiles.length">
          <view class="w-150 h-150 bg-CCCCCC mr-30 mb-10" v-for="(imagesItem,imagesIndex) in errphotoFiles" :key="imagesIndex">
            <image class="w-150 h-150" :src="imagesItem.url" @tap="previewImage(errphotoFiles, imagesIndex)"></image>
          </view>
        </view>
        <view v-else class="w-150 h-150 bg-CCCCCC flex flex-column align-center justify-center">
          <image class="w-47 h-40" src="@/static/images/common/empty.png"></image>
          <text class="color-fff fz-24 lh-33 mt-10">无现场图片</text>
        </view>
      </view>

      <sub-title title="异常修正"></sub-title>
      <view class="flex align-center justify-between">
        <text class="fz-32 lh-45 m-tb-20 ml-40 ">{{ abnormalInfo.standardName || '-'}}</text>
        <view v-if="abnormalInfo.type == 1" class="flex align-center mr-40">
          <text
              class="fz-32 lh-45 m-tb-20 block color-2D8CF0 mr-10 w-150 text-right"
              @tap="StatusCheckModalShow"
          >
            请选择
          </text>
          <image
              class="h-28 w-14"
              src="@/static/images/common/toPathV2.png"
          ></image>
        </view>
      </view>

      <!--单选标准-->
      <view v-if="abnormalInfo.type == 0">
        <u-radio-group class="w-full" v-model="result" active-color="#19BE6B" size="40" :disabled="isFixed || abnormalInfo.status == 1">
          <view class="flex w-full flex-column">
            <view class="w-full flex align-center p-lr-40 mb-10 oh" v-for="(item, index) in list" :key="index">
              <u-radio
                  class="flex w-full border-333333 br-10 pl-25"
                  label-size="32"
                  :name="item.name"
              >
                {{item.name}}
              </u-radio>
            </view>
          </view>
        </u-radio-group>
      </view>

      <!--多选标准-->
      <view
          class="pt-24 pb-10 p-lr-40 fz-32 status wrap statusCheckedList text-ellipsis"
          v-if="result && result.length && abnormalInfo.type == 1"
      >
        <text
            v-for="(item, index) in statusCheckedList"
            :key="index"
            :class="[abnormalInfo.normal.split(',').includes(item) ?'color-19BE6B':'color-FF6262']"
        >
          {{item}}
        </text>
      </view>

      <!--填值标准-->
      <view class="flex align-center justify-between m-lr-20 p-lr-20 fz-32 color-888888 border-888888 br-10 h-80 lh-80" v-if="abnormalInfo.type == 2" @tap="showInput">
        <text class="flex1 color-000000"  v-if="value || value === 0"> {{ value }} </text>
        <text class="flex1 color-888888" v-else>点击输入</text>
        <text>{{abnormalInfo.unit || '-'}}</text>
      </view>

      <!--状态多选模态框-->
      <u-modal v-model="isStatusCheckModalShow" :show-confirm-button="false" :show-title="false" border-radius="20"
               mask-close-able>
        <view class="w-full flex flex-column align-center p-lr-50">
          <scroll-view scroll-y :show-scrollbar="true" class="w-full options_container">
            <u-checkbox-group class="w-full" @change="checkboxGroupChange" size="40">
              <view class="w-full flex flex-column">
                <view v-for="(item, index) in statusList" :key="index" class="min-h-160 w-full flex align-center border-bottom-CCCCCC">
                  <u-checkbox class="w-full flex" :name="item.name" v-model="item.checked" :disabled="false" shape="circle" active-color="#19BE6B">
                    <view class="ml-30">
                      <text class="font-bold color-333333 fz-32" > {{ item.name }} </text>
                    </view>
                  </u-checkbox>
                </view>
              </view>
            </u-checkbox-group>
          </scroll-view>
          <view class="flex align-center justify-center m-tb-50">
            <view class="border-2D8CF0 w-120 h-60 border-box color-2D8CF0 fz-28 text-center lh-60 br-5 mr-50"
                  @tap="statusCheckCancle">
              <text>取消</text>
            </view>
            <view class="bg-2D8CF0 w-120 h-60 color-fff fz-28 text-center lh-60 br-5" @tap="statusCheckConfirm">
              <text>提交</text>
            </view>
          </view>
        </view>
      </u-modal>

      <u-modal border-radius="20" :show-confirm-button="false" :show-title="false" mask-close-able v-model="isModalShow">
        <view class="h-150 flex align-center justify-center fz-30 font-bold">
          <image class="mr-20 w-38 h-38" src="@/static/images/mine/error.png"></image>
          <text>{{modalContent}}</text>
        </view>
      </u-modal>

      <!--图片上传中模态框-->
      <u-modal border-radius="20" :show-confirm-button="false" :show-title="false" v-model="isUploading">
        <view class="h-200 flex flex-column align-center justify-center font-bold color-888888 lh-33">
          <text class="mb-10">图片上传中</text>
          <u-loading mode="circle"></u-loading>
        </view>
      </u-modal>

      <canvas class="absolute top-99999"
              v-if="windowWidth !== 0 && windowHeight !== 0"
              :style="{'width':`${windowWidth}px`,'height': `${windowHeight}px`}"
              :canvas-id="`mycanvas`" >
      </canvas>

      <!--拍照模块-->
      <view class="p-tb-20 pl-40" v-if="abnormalInfo.isTakePhoto">
        <text class="fz-32 color-888888 lh-45">拍照</text>
        <text class="color-FF6262 fz-32">*</text>
        <view class="mt-10 flex flex-wrap">
          <!-- 图片缩略图  -->
          <view class="relative mr-30 mb-20" v-for="(item, index) in photoFiles" :key="index">
            <image
                class="h-150 w-150"
                :src="item.url"
                @tap="previewImage(photoFiles, index)"
            />
            <!--  移除图片的按钮  -->
            <view v-if="!isFixed && abnormalInfo.status == 0" class="absolute delBtn" @tap.stop="removeImage(item.id)">
              <image
                  class="h-24 w-24"
                  src="@/static/images/workList/delPhoto.png"
              />
            </view>
          </view>
          <view
              v-if="abnormalInfo.status == 0 && photoFiles.length < 6"
              class="h-150 w-150 mb-20 bg-CCCCCC flex align-center justify-center"
              @tap="uploadImage"
          >
            <image class="h-50 w-50" src="@/static/images/workList/camera.png"></image>
          </view>
          <view v-if="abnormalInfo.status == 1 && !photoFiles.length"
                class="w-150 h-150 bg-CCCCCC flex flex-column align-center justify-center"
          >
            <image class="w-47 h-40" src="@/static/images/common/empty.png"></image>
            <text class="color-fff fz-24 lh-33 mt-10">暂无图片</text>
          </view>
        </view>
      </view>
    </view>
    <view v-if="!isFixed && abnormalInfo.status == 0" class="h-150 sticky w-full flex align-center justify-center bottom0 border-top-EEEEEE bg-fff z-1000">
      <view class="w-250 h-80 lh-80 text-center color-fff fz-30 br-10 bg-19BE6B" @tap.stop="fix">
        <text>修复异常</text>
      </view>
      <view class="w-250 h-80 lh-80 text-center color-fff fz-30 br-10 bg-19BE6B ml-40" @tap.stop="toRepair">
        <text>关联报修</text>
      </view>
    </view>

    <!--异常值未修正或必拍照巡检项未拍照提示框-->
    <u-modal v-model="isShowConfirmModal" :show-confirm-button="false" :show-title="false" border-radius="20"
             mask-close-able>
      <view class="w-full flex flex-column align-center p-lr-50">
        <view class="lh-center color-333 fz-30 fw-700 p-tb-42 border-bottom-CCCCCC w-full">{{confirmModalContent}}</view>
        <view class="flex align-center justify-center m-tb-50">
          <view class="border-2D8CF0 bg-2D8CF0 w-120 h-60 border-box color-fff fz-28 text-center lh-60 br-5 mr-50"
                @tap="confirmFixAbnormal">
            <text>确定</text>
          </view>
          <view class="border-2D8CF0 w-120 h-60 border-box color-2D8CF0 fz-28 text-center lh-60 br-5"
                @tap="isShowConfirmModal = false">
            <text>取消</text>
          </view>
        </view>
      </view>
    </u-modal>

    <!--键盘上方显示填值标准区域-->
    <popup-input :isShow="isShow" @close="close" @confirm="valueChange" :value="value"></popup-input>
  </view>
</template>

<script>
import dayjs from '@/libs/dayjs.min.js'
import SubTitle from "@/components/SubTitle/SubTitle";
import { abnormal, fixAbnormal } from "@/api/inspection/abnormal";
import PopupInput from "./components/PopUpInput";
import uploadMaskImg from "@/mixins/uploadMaskImg";
export default {
  name: "handle-error",
  components: {PopupInput, SubTitle},
  mixins: [uploadMaskImg],
  onLoad(options){
    this.abnormalId = options.abnormalId
    this.fromCheckedHistory = options?.fromCheckedHistory || 2
    abnormal(this.abnormalId).then( res => {
      this.abnormalInfo = res.data
      this.init()
    })
  },
  created(){
    uni.onKeyboardHeightChange(res => {
      this.$store.commit('SET_KEYBOARDHEIGHT', res.height)
    })
  },
  data(){
    return {
      abnormalId:'',
      abnormalInfo:'',
      value:'',
      result:'',
      isStatusCheckModalShow:false,
      statusList:[],
      oldStatusList: [],
      list:[],
      isModalShow:false,
      modalContent: '',
      isFixed:false,
      photoFiles:[],//图片链接列表
      errphotoFiles:[],//异常图片链接列表
      isUploading:false,
      uploadState:[],
      statusCheckedList:[],
      statusCheckedListTemp: [],
      ossIdList:[],
      fromCheckedHistory:0,// 0 巡检详情进入 1 巡检历史进入 2 异常列表进入
      isShow: false, //键盘上方输入框显隐
      isShowConfirmModal: false, //异常值未修正或必拍照巡检项未拍照提示框显隐
      confirmModalContent: '',
    }
  },
  methods:{
    close(value){
      this.isShow = value
    },
    showInput(){
      if(this.isFixed || this.abnormalInfo.status === '1'){
        return
      }
      this.isShow = true
      this.$store.commit('SET_INPUTVALUE', this.value)
    },
    valueChange(content){
      if(content === null || content === undefined || content === ''){
        this.value = ''
        return
      }
      this.value = content.toString().trim()
      if(isNaN(Number(this.value))){
        this.modalContent = '输入值不正确，请重新输入！'
        this.isModalShow = true
        this.value = this.abnormalInfo.value
        return
      }
      if(this.value < -9999 || this.value > 9999){
        this.modalContent = '数值必须在-9999到9999之间！'
        this.isModalShow = true
        this.value = this.abnormalInfo.value
        return
      }
    },
    init(){
      if(this.abnormalInfo.type == 0 ){
        this.abnormalInfo.normal.split(',').forEach(item => {
          this.list.push({status: 'normal', name: item})
        })
        this.abnormalInfo.abnormal.split(',').forEach(item => {
          this.list.push({status: 'abnormal', name: item})
        })
      }else if(this.abnormalInfo.type == 1 ) {
        this.abnormalInfo.normal.split(',').forEach(item => {
          this.statusList.push({status: 'normal', name: item, checked: false})
        })
        this.abnormalInfo.abnormal.split(',').forEach(item => {
          this.statusList.push({status: 'abnormal', name: item, checked: false})
        })
      }

      this.abnormalInfo.value = this.abnormalInfo.value || this.abnormalInfo.value == 0 ? parseFloat(this.abnormalInfo.value) : ''
      this.result = this.abnormalInfo.result
      if(this.result){
        this.statusCheckedList = this.result.split(',')
        this.statusCheckedListTemp = this.result.split(',')
        this.result.split(',').forEach(item => {
          this.statusList.forEach(statusListItem => {
            if(statusListItem.name == item){
              statusListItem.checked = true
            }
          })
        })
      }
      this.oldStatusList = JSON.parse(JSON.stringify(this.statusList))
      this.value = this.abnormalInfo.value
      this.errphotoFiles = this.abnormalInfo.errorImages.length ? this.abnormalInfo.errorImages.map(item => ({
        url:item.url,
        id: item.ossId
      })): []
      this.photoFiles = this.abnormalInfo.images.length ? this.abnormalInfo.images.map(item => ({
        url:item.url,
        id: item.ossId
      })) : []
      this.ossIdList = this.abnormalInfo.images ? this.abnormalInfo.images.map(item => item.ossId) : []
    },

    //多选状态点击请选择
    StatusCheckModalShow(){
      if(!this.isFixed && this.abnormalInfo.status == 0){
        this.isStatusCheckModalShow = true
      }
    },
    //输入框是否为异常值
    isAbnormalValue(){
      return this.value && this.value < parseFloat(this.abnormalInfo.lowerLimit) || this.value > parseFloat(this.abnormalInfo.ceiling)
    },
    //单选或多选状态是否含异常值
    isAbnormalResult(){
      if(this.abnormalInfo.type == 0){
        return this.list.find(item => {
          return item.name === this.result
        })?.status === 'abnormal'
      }else if(this.abnormalInfo.type == 1){
        if(this.result){
          return this.result.split(',').some(resultItem => {
            return this.statusList.find(item => {
              return item.name === resultItem
            })?.status === 'abnormal'
          })
        }else{
          return false
        }
      }
    },
    //多选框值改变
    checkboxGroupChange(e){
      this.statusCheckedListTemp = e
    },
    //状态选择取消按钮
    statusCheckCancle(){
      this.isStatusCheckModalShow = false
      this.statusList = JSON.parse(JSON.stringify(this.oldStatusList))
    },
    //状态选择提交按钮
    statusCheckConfirm(){
      this.statusCheckedList = this.statusCheckedListTemp
      const resultTemp = this.statusCheckedList.reduce((pre, next) => {
        if(!pre.length){
          return next
        }else{
          pre = pre + ',' + next
          return pre
        }
      },'')
      if(!resultTemp){
        this.isModalShow = true
        this.modalContent = '请至少选择一个结果！'
        return
      }
      this.oldStatusList = JSON.parse(JSON.stringify(this.statusList))
      this.result = resultTemp
      //隐藏状态选择模态框
      this.isStatusCheckModalShow = false
    },
    // 上传图片
    uploadImage(e) {
      if(this.isFixed) return
      this.uploadMaskImg()
    },
    // 水印内容
    maskContent(ctx, image){
      ctx.strokeText(this.abnormalInfo.workOrderName || '-',image.width * 0.092,image.width * 0.18);
      ctx.fillText(this.abnormalInfo.workOrderName || '-', image.width * 0.092, image.width * 0.18)

      ctx.strokeText(this.abnormalInfo.deviceName || '-',image.width * 0.092,image.width * 0.23);
      ctx.fillText(this.abnormalInfo.deviceName || '-', image.width * 0.092, image.width * 0.23)

      ctx.strokeText(this.$store.getters.staffName || '-',image.width * 0.092,image.width * 0.28);
      ctx.fillText(this.$store.getters.staffName || '-', image.width * 0.092, image.width * 0.28)

      ctx.strokeText(dayjs().format('YYYY-MM-DD HH:mm:ss'),image.width * 0.092,image.width * 0.33);
      ctx.fillText(dayjs().format('YYYY-MM-DD HH:mm:ss'), image.width * 0.092, image.width * 0.33)
    },

    //水印图片上传成功后回调函数
    uploadSuccessCallback(data){
      this.ossIdList.push(data.data.ossId)
      this.photoFiles.push({
        url: data.data.url,
        id: data.data.ossId,
      });
    },
    // 点击预览
    previewImage(photoFiles, index) {
      const urls = photoFiles.map(item => {
        return item.url
      })
      uni.previewImage({
        urls, //需要预览的图片链接列表
        current: index,
        indicator: "none", //图片指示器样式 "default" - 底部圆点指示器； "number" - 顶部数字指示器； "none" - 不显示指示器
      });
    },

    // 删除图片
    removeImage(id) {
      this.photoFiles = this.photoFiles.filter(item => {
        return item.id !== id
      })
      this.ossIdList = this.ossIdList.filter(item => {
        return item !== id
      })
      this.$emit('calcHeight')
    },
    //修复异常
    fix(){
      if(this.isAbnormalValue() || this.isAbnormalResult()){
        this.isShowConfirmModal = true
        this.confirmModalContent = '巡检项未调整为正常值。是否继续修复异常？'
      }else{
        if(this.abnormalInfo.isTakePhoto && !this.ossIdList.length){
          this.isShowConfirmModal = true
          this.confirmModalContent = '未补充照片，是否继续修复异常？'
        }else{
          this.fixAbnormal()
        }
      }
    },
    toRepair(){
      this.$tab.navigateTo(`/pages/repair/connect-repair?hospitalId=${this.abnormalInfo.hospitalId}&abnormalId=${this.abnormalInfo.abnormalId}`)
    },
    confirmFixAbnormal(){
      this.fixAbnormal()
      this.isShowConfirmModal = false
    },
    fixAbnormal(){
      let data = {
        value: this.value,
        result: this.result,
        type: this.abnormalInfo.type,
        abnormalId: this.abnormalId,
        ossIdList: this.ossIdList,
        workOrderStatus: 0,
        workOrderDeviceId: this.abnormalInfo.workOrderDeviceId
      }
      fixAbnormal(data).then(res => {
        if(res.code == 200){
          this.isFixed = true
        }
      })
    },
    toAssignmentDetail(){
      if(this.fromCheckedHistory == 0){
        uni.navigateBack({
          delta: 2
        });
      }
      else{
        this.$tab.navigateTo('/pages/work/work-order-detail?workOrderId=' + this.abnormalInfo.workOrderId)
      }
    }
  },
  options: { styleIsolation: "shared" },
}
</script>
<style>
page{
  background-color: #fff;
}
</style>
<style lang="scss" scoped>
.normal /deep/ .u-input__input {
  color: #19BE6B;
}
.warn /deep/ .u-input__input {
  color: #FF6262;
}
/deep/ .u-input__input{
  font-size: 32rpx !important;
}
/deep/ .u-checkbox{
  width: 100% !important;
  display: flex !important;
  line-height: 1;
}
/deep/ .u-checkbox__label{
  flex: 1 !important;
  width: 560rpx;
  padding: 55rpx 0;
}
/deep/ .u-radio{
  width: 100% !important;
  display: flex !important;
  line-height: 1;
}
/deep/ .u-radio__label{
  flex: 1 !important;
  padding: 24rpx 0 24rpx 24rpx !important;
  width: 560rpx;
}
.delBtn{
  top: -12rpx;
  right: -12rpx;
}
.wrap{
  word-wrap: break-word;
  word-break: normal;
  overflow: hidden;
}
.options_container{
  max-height: 520rpx;
  overflow: scroll;
}
.statusCheckedList > text:not(:last-child):after {
  content: ',';
}
.test{
  overflow-x: hidden;
}
</style>
